<template>
  <div class="huawei-index">
    <!-- 顶部导航栏 -->
    <header class="huawei-header">
      <div class="header-container">
        <!-- Logo区域 -->
        <div class="logo-section" @click="$router.push('/')">
          <div class="logo-graphic">
            <div class="green-part"></div>
            <div class="dark-part"></div>
          </div>
          <span class="shop-name">华为商城</span>
        </div>

        <!-- 主导航菜单 -->
        <nav class="nav-section">
          <div class="nav-menu">
            <a
                v-for="item in navItems"
                :key="item.id"
                :class="['nav-item', { active: currentRoute === item.route }]"
                @click="handleNavClick(item)"
            >
              {{ item.name }}
            </a>
          </div>
        </nav>

        <!-- 用户操作区 -->
        <div class="user-section">
          <el-button link @click="showLoginDialog = true" v-if="!authStore.isLoggedIn">
            <el-icon><User /></el-icon>
            登录
          </el-button>
          <el-button link @click="showRegisterDialog = true" v-if="!authStore.isLoggedIn">
            <el-icon><Edit /></el-icon>
            注册
          </el-button>
          <div class="user-info" v-if="authStore.isLoggedIn">
            <el-avatar :size="32" class="user-avatar">
              {{ authStore.user?.name?.charAt(0) || 'U' }}
            </el-avatar>
            <span class="user-name">{{ authStore.user?.name || authStore.user?.username }}</span>
            <el-button link @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出
            </el-button>
          </div>
          <el-button link @click="handleCartClick">
            <el-icon><ShoppingCart /></el-icon>
            购物车({{ cartStore.totalItems }})
          </el-button>
        </div>
      </div>
    </header>

    <!-- 登录弹窗 -->
    <el-dialog
        v-model="showLoginDialog"
        title="登录华为商城"
        width="400px"
        :before-close="handleLoginClose"
        center
    >
      <el-form
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          size="large"
          @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              :loading="loginLoading"
              @click="handleLogin"
              class="login-btn"
          >
            {{ loginLoading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <span>还没有账号？</span>
          <el-link type="primary" @click="showRegisterFromLogin">立即注册</el-link>
        </div>
      </template>
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
        v-model="showRegisterDialog"
        title="用户注册"
        width="450px"
        :before-close="handleRegisterClose"
        center
    >
      <el-form
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormRef"
          label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名（3-20位字符）"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码（6-20位字符）"
              show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱地址"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showRegisterDialog = false">取消</el-button>
        <el-button
            type="primary"
            :loading="registerLoading"
            @click="handleRegister"
        >
          {{ registerLoading ? '注册中...' : '注册' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 页面内容区域 -->
    <main class="main-content">
      <router-view />
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { User, Edit, ShoppingCart, SwitchButton } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const authStore = useAuthStore()

// 导航菜单项
const navItems = ref([
  { id: 'home', name: '首页', route: '/' },
  { id: 'phone', name: '手机', route: '/phones' },
  { id: 'tablet', name: '平板', route: '/tablets' },
  { id: 'laptop', name: '笔记本', route: '/laptops' },
  { id: 'wearable', name: '智能穿戴', route: '/wearables' }
])

// 计算当前路由
const currentRoute = computed(() => route.path)

// 弹窗控制
const showLoginDialog = ref(false)
const showRegisterDialog = ref(false)

// 登录表单
const loginFormRef = ref()
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const loginLoading = ref(false)

// 注册表单
const registerFormRef = ref()
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
})

const registerLoading = ref(false)

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 导航点击
const handleNavClick = (item) => {
  router.push(item.route)
}

// 购物车点击
const handleCartClick = () => {
  if (!authStore.isLoggedIn) {
    ElMessage.warning('请先登录后查看购物车')
    showLoginDialog.value = true
    return
  }
  router.push('/cart')
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loginLoading.value = true

    // 调用登录接口
    await authStore.login(loginForm)

    ElMessage.success('登录成功！')
    showLoginDialog.value = false

    // 清空登录表单
    Object.assign(loginForm, {
      username: '',
      password: ''
    })

    // 加载用户购物车
    cartStore.loadUserCart()
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请检查用户名和密码')
  } finally {
    loginLoading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    registerLoading.value = true

    // 调用注册接口
    await authStore.register(registerForm)

    ElMessage.success('注册成功！请使用新账号登录')
    showRegisterDialog.value = false

    // 清空注册表单
    Object.assign(registerForm, {
      username: '',
      password: '',
      confirmPassword: '',
      phone: '',
      email: ''
    })

    // 显示登录弹窗
    showLoginDialog.value = true
  } catch (error) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    registerLoading.value = false
  }
}

// 退出登录
const handleLogout = () => {
  authStore.logout()
  cartStore.clearCartDisplay()
  ElMessage.success('已退出登录')
}

// 从登录跳转到注册
const showRegisterFromLogin = () => {
  showLoginDialog.value = false
  showRegisterDialog.value = true
}

// 弹窗关闭处理
const handleLoginClose = (done) => {
  loginFormRef.value?.clearValidate()
  Object.assign(loginForm, {
    username: '',
    password: ''
  })
  done()
}

const handleRegisterClose = (done) => {
  registerFormRef.value?.clearValidate()
  Object.assign(registerForm, {
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    email: ''
  })
  done()
}

// 监听登录状态变化
watch(() => authStore.isLoggedIn, (newVal) => {
  if (newVal) {
    // 用户登录时加载购物车
    cartStore.loadUserCart()
  } else {
    // 用户登出时清空购物车显示
    cartStore.clearCartDisplay()
  }
})

onMounted(() => {
  // 初始化认证状态
  authStore.initAuth()

  // 监听登录弹窗显示事件
  window.addEventListener('showLoginDialog', () => {
    showLoginDialog.value = true
  })
})
</script>

<style scoped>
.huawei-index {
  min-height: 100vh;
  background: #ffffff;
}

.huawei-header {
  background: #ffffff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  height: 60px;
  position: sticky;
  top: 0;
  z-index: 1000;
  border-bottom: 1px solid #f0f0f0;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 20px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.logo-graphic {
  width: 32px;
  height: 32px;
  display: flex;
  position: relative;
}

.green-part {
  width: 20px;
  height: 32px;
  background: #00c200;
  border-radius: 2px 0 0 2px;
}

.dark-part {
  width: 12px;
  height: 32px;
  background: #333333;
  border-radius: 0 2px 2px 0;
}

.shop-name {
  font-size: 20px;
  font-weight: bold;
  color: #c7000a;
}

.nav-section {
  flex: 1;
  display: flex;
  justify-content: center;
}

.nav-menu {
  display: flex;
  align-items: center;
  gap: 0;
  height: 60px;
}

.nav-item {
  padding: 0 24px;
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  color: #333333;
  text-decoration: none;
  cursor: pointer;
  position: relative;
  transition: color 0.3s ease;
  border-bottom: 3px solid transparent;
  white-space: nowrap;
}

.nav-item:hover {
  color: #1890ff;
}

.nav-item.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #333;
}

.user-avatar {
  background: linear-gradient(45deg, #ff6b6b, #ffd93d);
}

.user-name {
  font-size: 14px;
  font-weight: 500;
}

.main-content {
  padding-top: 0;
  min-height: calc(100vh - 60px);
}

/* 弹窗样式 */
.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

.dialog-footer {
  text-align: center;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  color: #666;
}

.dialog-footer .el-link {
  margin-left: 5px;
}

:deep(.el-dialog) {
  border-radius: 10px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 20px;
  margin: 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding: 15px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 15px;
  }

  .nav-item {
    padding: 0 15px;
    font-size: 14px;
  }

  .user-section {
    gap: 10px;
  }
}
</style>